
// 导入express 模块
const express = require("express")
// 创建app实例
const app = express()
const path = require('path');
const userRouter = require("./router/user.js")
const userinfoRouter = require("./router/userinfo.js")
const role = require("./router/role.js")
const right = require("./router/right.js")
const goods = require("./router/goods.js")
const order = require("./router/order.js")
const shop = require("./router/shop.js")
const analysis = require("./router/analysis")
const cart = require("./router/user_cart.js")
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser');

// ​
app.use(cookieParser());//使用cookie-parser// 
// 导入 cors 中间件
const cors = require('cors')
app.use(express.urlencoded({ extended: false }))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())



const expressJWT = require('express-jwt')

const config = require("./config/config")
const joi = require('joi')



// 将 cors 注册为全局中间件
app.use(cors())

app.use(function(req,res,next){
    res.cc = function (err,code = 500){
        res.send({
            code,
            // 状态描述，判断 err 是 错误对象 还是 字符串
            msg:err instanceof Error ? err.message : err
        })
    }
    next()
})
app.use(express.static(path.join(__dirname,'./images')));

//高版本算法发生改变
app.use(expressJWT({secret:config.jwtSecretKey,algorithms:['HS256']}).unless({path:['/user/login','/user/shoplogin',/^\/$png/,'/goods/uploadImg']}))

app.use("/user",userRouter)
app.use("/userinfo",userinfoRouter)
app.use("/goods",goods)
app.use("/role",role)
app.use("/right",right)
app.use("/order",order)
app.use('/shop',shop)
app.use('/cart',cart)
app.use("/analysis",analysis)


// 错误中间件
app.use(function (err, req, res, next) {
    // 数据验证失败
    if (err instanceof joi.ValidationError) return res.cc(err)
    if (err.name === 'UnauthorizedError') {
        return res.cc("无效Token",401)
      }
    // 未知错误
    return res.cc(err)
  })
app.listen(3007,()=>{

    console.log("serve at http://127.0.0.1:3007");
})